//
//  ConfirmReceiptVC.m
//  ProjectforHDX
//
//  Created by yinda on 16/8/3.
//  Copyright © 2016年 H.DX. All rights reserved.
//

#import "ConfirmReceiptVC.h"
#import "ConfirmReceiptCell.h"
#import "ConfirmReceiptModels.h"
#import "CSMyOrderConfirmingTVC.h"
#import "CunjianDetailVC.h"

@interface ConfirmReceiptVC ()<UITableViewDataSource,UITableViewDelegate>
{
    NSMutableArray *dataArray;
    BOOL   isMJRefresh;
    NSInteger _page;
}
@property (nonatomic, strong) UITableView *tableView;

@end

@implementation ConfirmReceiptVC

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [dataArray removeAllObjects];
    [self addHeader];
    [self addFooter];
    [self requestDatas];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    dataArray = [[NSMutableArray alloc]init];
    _page = 1;
    
    [self requestViews];
}

- (void)requestViews{
    
    self.navColor = SYSTEM_COLOR;
    self.labnav.text = [UtilCheck language:@"setting.messageList"];
    // 我的消息
    [self.labnav setFont:NavFontSize];
    [self.labnav setTextColor:[UIColor whiteColor]];
    
    self.mBackColor =[UIColor groupTableViewBackgroundColor];
    
    // tableView
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, -35, SCREEN_WIDTH, SCREEN_HEIGHT) style:(UITableViewStyleGrouped)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    [self.tableView registerClass:[ConfirmReceiptCell class] forCellReuseIdentifier:@"ConfirmReceiptCell"];
    
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    [self.tableView setBackgroundColor:[Toolobject getColorByRGB:244 green:248 blue:251 alpha:1]];
    [self.view addSubview:self.tableView];
    isMJRefresh = YES;
    
    
    
}
- (void)requestDatas
{
    
    [[BDHUD sharedManager] showBDHUD:self.view title:[THMangerTool language:@"HUD.title"]];
    
    NSMutableDictionary *typeDic = [[NSMutableDictionary alloc]init];
    [typeDic setObject:self.type forKey:@"type"];
    [typeDic setObject:[NSString stringWithFormat:@"%ld",(long)_page] forKey:@"page"];
    [typeDic setObject:@"10" forKey:@"size"];
    NSString *key = [THMangerTool getKey];
    [typeDic setObject:key forKey:@"key"];
    
    [AFHttpTool postJsonDatawithUrl:@"messages_1_2" parameters:typeDic success:^(id responseObject) {
        isMJRefresh = YES;
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
        
        [[BDHUD sharedManager] dismissHUD];
        
        if ([[[responseObject objectForKey:@"head"] objectForKey:@"status"] intValue] == 1) {
            NSArray *dataArr = [responseObject objectForKey:@"data"];
            
            if (_page == 1) {
                [dataArray removeAllObjects];
            }
            for (NSDictionary *dataDic in dataArr) {
                ConfirmReceiptModels *models = [[ConfirmReceiptModels alloc]init];
                models.title = dataDic[@"title"];
                models.content = dataDic[@"content"];
                models.time = dataDic[@"time"];
                models.orderCode = dataDic[@"orderCode"];
                models.isRead = dataDic[@"isRead"];
                models.messageID = dataDic[@"messageID"];
                models.type_operation = dataDic[@"type_operation"];
                models.code_operation = dataDic[@"code_operation"];
                [dataArray addObject:models];
            }
            [self.tableView reloadData];
        }else {
            [[BDHUD sharedManager] dismissHUD];
            [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
        }
        
    } fail:^(id responseObject, NSError *error) {
        
        isMJRefresh = YES;
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
        
        [[BDHUD sharedManager] dismissHUD];
        
        if ([[error.userInfo objectForKey:@"NSLocalizedDescription"] isEqualToString:@"请求超时。"]) {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.time.out"]];
        }else {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.network.interruption"]];
        }
    }];
}


#pragma mark- TalbleView Delegate&DataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ConfirmReceiptModels *models = dataArray[indexPath.row];
    
    NSString *string = models.content;
    CGSize maxSize = CGSizeMake(tableView.bounds.size.width - 20 , MAXFLOAT);
    CGRect rect = [string boundingRectWithSize:maxSize options:NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13.5]} context:nil];
    
    
    return rect.size.height + 100 -21 - 5;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ConfirmReceiptCell * cell = [[ConfirmReceiptCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ConfirmReceiptCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UtilCheck hexStringToColor:@"f6f7fb" alpha:1];
    if (dataArray.count != 0) {
        ConfirmReceiptModels *models = dataArray[indexPath.row];
        
        RZCustomLable *timeLabel = [[RZCustomLable alloc]initWithFrame:CGRectMake(0, 5, tableView.width, 20)];
        timeLabel.text = models.time;
        timeLabel.textColor = [UtilCheck hexStringToColor:@"e1e1df" alpha:1];
        
        timeLabel.font = [UIFont fontWithName:@"ArialMT" size:11];
        [timeLabel setTextAlignment:NSTextAlignmentCenter];
        [cell.contentView addSubview:timeLabel];
        NSString *str = models.content;
        CGSize maxSize = CGSizeMake(tableView.bounds.size.width - 20, MAXFLOAT);
        CGRect rec = [str boundingRectWithSize:maxSize options:NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13.5]} context:nil];
        UIView *cellView = [[UIView alloc]initWithFrame:CGRectMake(10, 30, tableView.bounds.size.width - 20, rec.size.height + 44)];
        cellView.backgroundColor = [UIColor whiteColor];
        
        NSString *string = models.title;
        CGRect  rect = [string boundingRectWithSize:CGSizeMake(MAXFLOAT, 17.f) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]} context:nil];
        RZCustomLable *titleLabel = [[RZCustomLable alloc]initWithFrame:CGRectMake(5, 5, rect.size.width - rect.size.width / 6, 21)];
        titleLabel.text = string;
        timeLabel.textColor = [UtilCheck hexStringToColor:@"252525" alpha:1];
        titleLabel.font = [UIFont fontWithName:@"ArialMT" size:14];;
        [cellView addSubview:titleLabel];
        
        if (![[NSString  stringWithFormat:@"%@",models.isRead] isEqualToString:@"1"]) {
            RZCustomImageView *fetchImageView = [[RZCustomImageView alloc]initWithFrame:CGRectMake(titleLabel.bounds.size.width + 8, 8, 4, 4)];
            fetchImageView.image = BDFILEIMAGENAEM(@"UserCenter/news.png");
            [cellView addSubview:fetchImageView];
        }
        RZCustomLable *contentLabel = [[RZCustomLable alloc]initWithFrame:CGRectMake(5, 30, cellView.bounds.size.width- 30, rec.size.height)];
        contentLabel.font = [UIFont fontWithName:@"ArialMT" size:13.5];
        contentLabel.text = models.content;
        contentLabel.numberOfLines = 0;
        contentLabel.textColor = [UtilCheck hexStringToColor:@"666666" alpha:1];
        [cellView addSubview:contentLabel];
        RZCustomImageView *imageView = [[RZCustomImageView alloc]initWithFrame:CGRectMake(tableView.bounds.size.width - 35, cellView.height/2 - 5, 5, 10)];
        UIImage *image = BDFILEIMAGENAEM(@"default/iconfont-jinru");
        imageView.image = image;
        [cellView addSubview:imageView];
        
        
        [cell.contentView addSubview:cellView];
    }
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPat
{
    ConfirmReceiptModels *models = dataArray[indexPat.row];
    [[BDHUD sharedManager] showBDHUD:self.view title:[THMangerTool language:@"HUD.title"]];
    
    NSDictionary *dic = @{@"messageID":models.messageID};
    
    [AFHttpTool postJsonDatawithUrl:@"readMessage" parameters:dic success:^(id responseObject) {
        
        [[BDHUD sharedManager] dismissHUD];
        int typeint = [self.type intValue];
        if (typeint == 6) {
            CunjianDetailVC *vc = [[CunjianDetailVC alloc]init];
            vc.titlename = [models.type_operation intValue] == 2 ? [UtilCheck language:@"order.qudetail"]:[UtilCheck language:@"order.cundetail"];
            vc.orderCode = models.code_operation;
            vc.isQujian = [models.type_operation intValue] == 1 ? @"0" : @"1";
            [self.navigationController pushViewController:vc animated:YES];
        }
        else{
            CSMyOrderConfirmingTVC *tvc = [[CSMyOrderConfirmingTVC alloc]init];
            tvc.orderCode = models.orderCode;
            [self.navigationController pushViewController:tvc animated:YES];
        }
        
    } fail:^(id responseObject, NSError *error) {
        
        [[BDHUD sharedManager] dismissHUD];
        
        if ([[error.userInfo objectForKey:@"NSLocalizedDescription"] isEqualToString:@"请求超时。"]) {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.time.out"]];
        }else {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.network.interruption"]];
        }
    }];
    
}

//修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

//进入编辑模式，按下出现的编辑按钮后
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView setEditing:NO animated:YES];
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"你确定删除该消息？" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
            ConfirmReceiptModels *models = dataArray[indexPath.row];
            [[BDHUD sharedManager] showBDHUD:self.view title:[THMangerTool language:@"HUD.title"]];
            
            NSDictionary *dic = @{@"messageID":models.messageID};
            
            [AFHttpTool postJsonDatawithUrl:@"deleteSingleMessage" parameters:dic success:^(id responseObject) {
                
                [[BDHUD sharedManager] dismissHUD];
                NSLog(@"%@",responseObject);
                [self requestDatas];
                
            } fail:^(id responseObject, NSError *error) {
                
                [[BDHUD sharedManager] dismissHUD];
                
                if ([[error.userInfo objectForKey:@"NSLocalizedDescription"] isEqualToString:@"请求超时。"]) {
                    [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.time.out"]];
                }else {
                    [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.network.interruption"]];
                }
            }];
            
        }]];
        
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

//设置进入编辑状态时，Cell不会缩进
- (BOOL)tableView: (UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
    return NO;
}
//先要设Cell可编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

/**
 *  下拉刷新
 */
- (void)addHeader
{
    
    if(self.tableView.header==nil){
        __weak typeof(self) weakSelf = self;
        // 添加上拉刷新头部控件
        self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            if (isMJRefresh) {
                isMJRefresh = NO;
                _page = 1;
                [weakSelf requestDatas];
            }
            
        }];
        // 马上进入刷新状态
        [self.tableView.header beginRefreshing];
    }
}
/**
 *  上拉刷新
 */
- (void)addFooter
{
    
    if (self.tableView.footer==nil) {
        __weak typeof (self) weakSelf = self;
        self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            if (isMJRefresh) {
                _page ++;
                isMJRefresh = NO;
                [weakSelf requestDatas];
            }
        }];
    }
}

@end
